;((doc, Socket, storage, location) => {

  const oList = doc.querySelector('#list');
  const oMessage = doc.querySelector('#message');
  const oSendBtn = doc.querySelector('#send');
  
  const ws = new Socket('ws:localhost:8000');

  let username = ''

  const init = () => {
    bindEvent();
  }

  function bindEvent() {
    oSendBtn.addEventListener('click', handleSendClick, false);
    ws.addEventListener('open', handleOpen, false);
    ws.addEventListener('close', handleClose, false);
    ws.addEventListener('error', handleError, false);
    ws.addEventListener('message', handleMessage, false);
  }

  function handleSendClick() {
    console.log('send message');

    const msg = oMessage.value;

    if (!msg.trim().length) {
      return;
    }

    ws.send(JSON.stringify({
      usr: username,
      dateTime: new Date().getTime(),
      message: msg
    }))
   
    oMessage.value = '';
  }

  function handleOpen(e) {
    console.log('websocket open', e);
    username = storage.getItem('username');

    if (!username) {
      location.href = 'entry.html';
      return;
    }

  }

  function handleClose(e) {
    console.log('websocket close', e);
  } 

  function handleError(e) {
    console.log('websocket error', e);
  }

  function handleMessage(e) {
    console.log('websocket msg');
    const msgData = JSON.parse(e.data);
    oList.appendChild(createMsg(msgData));
  }

  function createMsg(data) {
    const { usr, dataTime, message } = data;

    const oItem = doc.createElement('li');
    oItem.innerHTML = `
      <p>
        <span>${ usr }</span>
        <i> ${ new Date(dateTime) }</i>
      </p>
      <p>消息: ${ message }</p>
    `;
    return oItem;
  }

  init();
  
})(document, WebSocket, localStorage, location);